package zkmcf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ZkMcf {

    private static String jdbcUrl = "jdbc:mysql://192.168.80.123:3306/azkaban?characterEncoding=utf-8&useSSL=false";
    private static JdbcConfig config = new JdbcConfig(jdbcUrl, "hive", "12345678");
    private static Connection con = null;

    //启动主函数
    public static void main(String[] args) throws InterruptedException, SQLException {
        createData();
//        deleteData();
    }
    private static void deleteData() throws SQLException, InterruptedException {
        //创建zk客户端
        ZkClient zkClient = new ZkClient("linux121:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        zkClient.delete("/jdbc");
        System.out.println("删除成功！");
    }
    private static void createData() throws SQLException, InterruptedException {
        //创建zk客户端
        ZkClient zkClient = new ZkClient("linux121:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        //连接数据库
        getConnection();
        boolean exists = zkClient.exists("/jdbc");
        if (!exists) {
            System.out.println("/jdbc数据信息为："+JSON.toJSONString(config));
            zkClient.createPersistent("/jdbc", JSON.toJSONString(config));
        }
        //监听节点
        zkClient.subscribeDataChanges("/jdbc", new IZkDataListener() {
            public void handleDataChange(String path, Object o) throws Exception {
                System.out.println("数据发生改变,当前path=" + path + " 数据对象=" + JSON.toJSONString(o));
                JSONObject object = JSONObject.parseObject(JSON.toJSONString(o));
                config.setPassword(object.getString("password"));
                config.setName(object.getString("name"));
                config.setUrl(object.getString("url"));
                //重新获取连接
                getConnection();
            }

            //数据节点删除
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path + "data is delete");
            }

        });
        Thread.sleep(Integer.MAX_VALUE);
    }


    public static void getConnection() throws SQLException {
        if (con != null) {
            con.close();
        }
        con = DriverManager.getConnection(config.getUrl(), config.getName(), config.getPassword());
        System.out.println(String.format("连接成功：host：%s name:%s password:%s", config.getUrl(), config.getName(), config.getPassword()));
    }
}
